package com.example.springbootgraduation.tengxunapi;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

//定义一个发送网络的工具
@Component
public class HttpUtils {

    /**
     * 发送网络请求的工具
     * @return
     */
    public String getData() throws Exception{
        //1、请求参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(10000)//设置一个超时时间
                .setConnectTimeout(10000)//链接超时
                .setConnectionRequestTimeout(10000)
                .build();
        //创建HttpClient客户端
        CloseableHttpClient httpClient = null;
        HttpGet request = null;
        //关闭HttpClient客户端
        CloseableHttpResponse response = null;

        try {
            //2、创建Httpclient
            httpClient = HttpClients.createDefault();
            //3、发送网络请求
            request = new HttpGet("http://c.m.163.com/ug/api/wuhan/app/data/list-total");
            //4、配置信息
            request.setConfig(requestConfig);
            //5、发送请求
            response = httpClient.execute(request);
            //6、查看状态码是否成功
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode==200){
                //7、解析数据
                HttpEntity entity = response.getEntity();//返回数据实体
                String string = EntityUtils.toString(entity, "utf-8");
                return string;
            }
        }finally {
            //关掉所有链接
            if (response!=null){
                //客户端关闭
                response.close();
            }
            if (request!=null){
                request.releaseConnection();
            }
            if (httpClient!=null){
                httpClient.close();
            }
        }
        return null;
    }
}
